﻿/**
 * @author @huntbao
 * @glodon utils
 */
;(function($){
	if(typeof Array.prototype.every != 'function'){
        Array.prototype.every = function(callback, thisObj){
            for (var i = 0, len = this.length; i < len; i++) {
                if (!callback.call(thisObj, this[i], i, this)) {
                    return false;
                }
            }
            return true;
        }
    }
    if(typeof Array.prototype.filter != 'function'){
        Array.prototype.filter = function(callback, thisObj){
            var res = [];
            for (var i = 0, len = this.length; i < len; i++) {
                if (callback.call(thisObj, this[i], i, this)) {
                    res[res.length] = this[i];
                }
            }
            return res;
        }
    }
    if(typeof Array.prototype.indexOf != 'function'){
        Array.prototype.indexOf = function(elem, fromIndex){
            fromIndex = fromIndex || 0;
            for (var i = fromIndex, len = this.length; i < len; i++) {
                if (this[i] === elem) {
                    return i;
                }
            }
            return -1;
        }
    }
    if(typeof Array.prototype.lastIndexOf != 'function'){
        Array.prototype.lastIndexOf = function(elem, fromIndex){
            fromIndex = fromIndex === undefined ? this.length : fromIndex;
            for (var i = fromIndex; -1 < i; i--) {
                if (this[i] === elem) {
                    return i;
                }
            }
            return -1;
        }
    }
    if(typeof Array.prototype.remove != 'function'){
        Array.prototype.remove = function(elem){
            var i = this.indexOf(elem);
            if (i !== -1) {
                this.splice(i, 1);
                return true;
            }
            else {
                return false;
            }
        }
    }
    if(typeof Array.prototype.some != 'function'){
        Array.prototype.some = function(callback, thisObj){
            for (var i = 0, len = this.length; i < len; i++) {
                if (callback.call(thisObj, this[i], i, this)) {
                    return true;
                }
            }
            return false;
        }
    }
    //form to json object
    $.fn.serializeObject = function(){
        var o = {}, a = this.serializeArray();
        $.each(a, function(){
            if(o[this.name] !== undefined){
                if(!o[this.name].push){
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            }else{
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
    var userAgent = navigator.userAgent.toLowerCase();
    try{
    	//for chrome
        var __console = window.console;
        window.console = null;
    }catch(err){
        
    }
	App.util = {
		contextPath: window._global.contextPath,
		accountURL: window._global.accountURL,
		documentURL: window._global.documentURL,
		databagURL: window._global.databagURL,
		browser: {
		    version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
		    chrome: /chrome/.test( userAgent ),
		    safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
		    opera: /opera/.test( userAgent ),
		    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
		},
		_tip: $('#page-global-tip'),
		actionTip: function(text, time){
            var self = this,
            tip = self._tip.stop(true);
            clearTimeout(self.animationTimer);
            tip.html(text).animate({
                top: 0
            }, function() {
                self.animationTimer = setTimeout(function() {
                    tip.animate({
                        top: -54
                    }, 200);
                }, time || 3000);
            });
		},
        showTip: function(text) {
            var tip = this._tip.animate({
                top: 0
            });
            text ? tip.html(text) : '';
        },
        hideTip: function(text, time) {
        	var self = this;
        	text ? self._tip.html(text) : '';
            clearTimeout(self.animationTimer);
            self.animationTimer = setTimeout(function() {
                self._tip.animate({
                    top: -54
                }, 200);
            }, time || 700);
        },
        formatSize: function(size){
        	if (size === undefined || /\D/.test(size)) {
                return 'N/A';
            }
            if (size > 1073741824) {
                return (size / 1073741824).toFixed(2) + ' GB';
            }if (size > 1048576) {
                return (size / 1048576).toFixed(2) + ' MB';
            }else if (size > 6) {
                return (size / 1024).toFixed(2) + ' KB';
            }else{
                return size + ' b';
            }
        },
        
        updateModel : function( model ){
            var modelex= model.extension ||  model.get && model.get("extension");
            var extension = modelex ?  modelex.toLowerCase() : "";
            if(model.folder || model.get && model.get("folder")){
            	extension = 'folder';
            }
		    var fileType = '',
		    noPreviewClass = '';
		    switch(extension){
    			case 'folder':
    				fileType = "folder";
	    			break;
	    		case 'jpeg':
		    	case 'jpg':
		    	   fileType = "jpg";
	    		    break;
		    	case 'tga' :
		    		fileType = "image";
		    		noPreviewClass = ' no-preview';
		    		break;
	    		case 'pdf':
	    			fileType = "pdf";
	    			break;
    			case 'xls':
    			case 'xlsx':
    				fileType = "excel";
	    			break;
    			case 'doc':
    			case 'docx':
    				fileType = "word";
	    			break;
    			case 'ppt':
    			case 'pptx':
    				fileType = "ppt";
    				break;
    			case 'htm':
    		    case 'html':
    			    fileType = 'html';
    			    noPreviewClass = ' no-preview';
    			    break;
    			case '7z':
    			    fileType = '7zip';
    			    noPreviewClass = '';
    			    break;
    			case 'ifc':
    			case 'gmsb':
    			case 'gfc':
    			case 'xml' :
    			case 'psd' :
		    	case 'zip':
		    	case 'jar':
		    	case 'rar':
		    	     fileType = extension;
		    	     noPreviewClass = ' no-preview';
                     break;
    			case 'txt':
    			case 'gif':
    			case 'bmp':
		    	case 'png':
    			case 'rvt':
	    		case 'dwg' :
    			    fileType = extension;
	    			break;
    			case 'gcl9':
    			case 'gcl10':
    				fileType = "gcl";
	    			break;
    			default:
                    fileType = 'other'
    			    noPreviewClass = ' no-preview';
	    			break;
		    }
		    model.fileClass = "item-icon icon_" + fileType;
		    model.noPreviewClass = noPreviewClass;
		    if(model.set){
                model.set({'fileClass': model.fileClass}, {silent: true});
                model.set({'noPreviewClass': model.noPreviewClass}, {silent: true});
                model.set({'inComplete': !model.get('revisionNumber')}, {silent: true});
                model.set({'inCompleteTitle': App.i18n.get('inCompletetip')}, {silent: true});
		    }
        },
        isEmail: function(v){
        	return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(v);
        },
        isMobile: function(v){
        	return /^\d{11}$/.test(v);
        },
        isGlodonAccount: function(v){
        	var self = this;
        	if(self.isEmail(v)) return true;
        	if(self.isMobile(v)) return true;
        	return false;
        },
        log: function(msg){
            if(__console && App.util.browser.chrome){
                function getErrorObject(){
                    try { throw Error('') } catch(err) { return err; }
                }
                var err = getErrorObject();
                var caller_line = err.stack.split("\n")[4];
                __console.log(msg);
                __console.info('==> ' + caller_line.trim());
            }
        },
        getParaValue: function(param, str){
            var hashs = (str ? str : location.hash.substr(2)).split('&'),
            findValue;
            _.each(hashs, function(hash){
                var h = hash.split('=');
                if(h[0] === param){
                    findValue = h[1];
                    return false;
                }
            });
            return findValue;
        },
        getLocaleDate: function(ms){
            var date = new Date(ms);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            var h = date.getHours();
            var mu = date.getMinutes();
            var s = date.getSeconds();
            function f(ff){
                return ff < 10 ? '0' + ff : ff;
            }
            m = f(m);
            h = f(h);
            d = f(d);
            mu = f(mu);
            s = f(s);
            return y + "/" + m + "/" + d + " " + h + ":" + mu + ":"+ s;
        },
        
        getIdWithPrefix: function(id){
            return 'g-' + id;
        },
        
        getIdWithPrefix2: function(id){
            return 'e-' + id;
        },
        
        removePrefixOfId: function(id){
            return id.replace(/g-/, '').replace(/e-/, '');
        },
        
        getContactsList: function(callback){
        	if(App.contactsList){
        	   callback && callback(App.contactsList);
        	   return;
        	}
            $.get(App.util.accountURL + '/communicateBook/listContactUser.json', function(data){
                callback && callback(data.items);
            	App.contactsList = data.items;
            });
        },
        
        getSuggestMemberList: function(callback){
            if(App.suggestMemberList){
               callback && callback(App.suggestMemberList);
               return;
            }
            (new Backbone.Collection).fetch({
                url: App.util.contextPath + '/project/member/suggestion',
                success: function(collection, options){
                	var data = collection.at(0).toJSON().items;
                    callback && callback(data);
                    App.suggestMemberList = data;
                }
            });
        }
	}
	App.log = App.util.log;
	$.browser = App.util.browser;
	App.userId = window.glodonPageConfig.userId;
	App.quota = window._global.quota;
})(jQuery);
